<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:29:32
 * @desc 微信支付配置
 */
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Model;
use Wechat\Lib\Tools;

//use app\comm\controller\WebLogController;
use app\comm\service\WeixinpayService;
use Endroid\QrCode\QrCode;
use \think\Loader;

class Weixinpay extends Controller{
	/**
	 * 微信支付生成二维码图片 -- 扫码支付
	 * @Author   lingyun
	 * @DateTime 2017-12-07T15:32:19+0800
	 * @return   [type]                   [description]
	 */
	public function create_paycode($parm){
		$post = input('param.');
		if(empty($post['order_sn'])){
			$this->error('缺少订单号',url('Index/index'));
		}
		//$post["openid"] =session("openid");
		$service = new WeixinpayService();		    //实例化微信支付类
		$pay_code = $service->_pay_payqrc($post);	//支付二维码
		$result = json_decode($pay_code,true);
		if($result['code'] == 0){
			halt($result['msg']);
		}else{
			halt($result['url']);
		}
		// halt($result);
	}

	/**
	 * 微信支付
	 * @Author   lingyun
	 * @DateTime 2017-12-07T16:50:27+0800
	 * @return   [type]                   [description]
	 */
	public function weixin_pay(){
	    $root = request()->domain();
		$post = input('param.');
//		halt($post);
		$result = $this->order_sn_check($post);
//		if($result["status"]==0){
//			$this->error($result["data"]);
//		}
		$out_trade_no = $post['order_sn'];
		$order = db('order')->where('order_sn',$out_trade_no)->find();
		$this->assign('final_amount',$order['final_amount']);
		$total_fee    =  $order['final_amount']*100;
//		$total_fee = 1;
		
		//微信浏览器端
		$pay          = 	& load_wechat('Pay');
		if(!empty(session("openid")) && is_weixin()){
			$pay          =  & load_wechat('Pay');
			$openid       =  session("openid");
			$notify_url   = $root.url("@index/notify/notifyweixinpay");
			$body         = "微信支付";
				
			$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "JSAPI");
			//更新预支付
			$prepaydata= ["prepayid"=>$prepayid];
			Db::table("ys_order")->where("order_sn",$out_trade_no)->update($prepaydata);

			$options = $pay->createMchPay($prepayid);
			$this->assign('options',json_encode($options));
			$this->assign('out_trade_no',$out_trade_no);
			$this->assign('sign',1);        //订单支付
			return view("weixinpay/weixin_pay");
		}
	   
		$body         =  "微信扫码支付";
		$notify_url   =  $root.url("@index/notify/notifyweixinpay");
        $prepayid 	  =  $pay->getPrepayId(null, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "NATIVE");
//        halt($prepayid);
   		//更新预支付
   		$prepaydata= ["prepayid"=>$prepayid];
		Db::table("ys_order")->where("order_sn",$out_trade_no)->update($prepaydata);
   		$this->assign('prepayid',$prepayid);
   		$this->assign('out_trade_no',$out_trade_no);
   		$this->assign('sign',1);        //订单支付
   		return view("weixinpay/weixin_code");
        exit;
	

	}

	//业务检查
	public function order_sn_check($post){
		$order = Db::table("ys_order")->where("order_sn",$post['order_sn'])->find();
		if(empty($order)){
            $this->assign('err_msg','找不该订单信息，请重新下单');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','重新下单');
            return $this->fetch('public/error');
            exit();
		}
		if($order["order_status"]!=0){
            $this->assign('err_msg','该订单已经支付，请勿重复支付');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','浏览其它商品');
            return $this->fetch('public/error');
            exit();
		}
		if(time()-3600>$order["addtime"]){
            $this->assign('err_msg','该订单已过期，请浏览其它商品');
            $this->assign('err_url',url('GoodsList/goods_list'));
            $this->assign('err_button','浏览其它商品');
            return $this->fetch('public/error');
            exit();
		}
		return ["status"=>1,"data"=>'可以支付'];
	}

	//ajax 轮询地址
	public function order_sn_ajax(){
        $order_sn = request()->get("out_trade_no");
        $order = db("order")->where("order_sn",$order_sn)->find();
//        if($order['addtime']<time()-864000){
//            return ['code'=>-1,'msg'=>'支付订单已关闭，请重新创建订单'];
//        }
        if($order["pay_status"] == 1){
            return ["status"=>1,"msg"=>'支付完成'];
        }else if($order['pay_status'] == -1){
            $msg = empty($order['charge_cn'])?'支付失败，请重新支付':$order['charge_cn'];
            return ["status"=>-1,"msg"=>$msg];
        }
	}

	/**
	 * 向支付平台查询订单状态
	 * @Author   lingyun
	 * @DateTime 2017-12-08T15:02:42+0800
	 * @return   [type]                   [description]
	 */
	public function check_order($order_sn){
		$service = new WeixinpayService();		//实例化微信支付类
		halt($service->checkorderstatus($order_sn));
	}

	//微信支付
	public function weixinzhifu(){
	    $root = request()->domain();
		$script = &  load_wechat('Script');
		$url = $this->request->url(true);
		$config = $script->getJsSign($url);
		$config["debug"] = true;
		$this->assign('config',json_encode($config));

		$post = input('param.');
		$pay = & load_wechat('Pay');
		$openid=session("openid");
		$body  = "微信支付";
		$out_trade_no =time().rand(1000,900000);
		$total_fee   = 1;
		$notify_url= $root.url("@index/notify/notifyweixinpay");
		$prepayid = $pay->getPrepayId($openid, $body, $out_trade_no, $total_fee, $notify_url, $trade_type = "JSAPI");
		$options = $pay->createMchPay($prepayid);
		unset($options["timestamp"]);
		$this->assign('options',json_encode($options));
		return view("weixinpay/weixinzhifu");
		//$qrc = $pay->getQrcPayUrl($post["order_sn"]);
	}

    /**
     * @Author lignyun
     * @Desc 会员充值 -- 微信端
     * 2018-03-21
     */
    public function recharge(){
        $root = request()->domain();
        $post = input('param.');
        //预支付检查订单
        $flag = $this->check_recharge_order($post);
        if($flag['status'] == 0){       //订单失败
            $this->assign('err_msg','订单信息有误，请重新充值');
            $this->assign('err_url',url('User/recharge'));
            $this->assign('err_button','重新充值');
            return $this->fetch('public/error');
            exit();
        }
//        $post['final_amount'] = $post['amount'];
//        $data = array(
//            'uid'=>$post['uid'],
//            'admin_id'=>0,
//            'store_id'=>0,
//            'order_id'=>0,
//            'order_sn'=>$post['order_sn'],
//            'pay_status'=>0,
//            'pay_type'=>$post['pay_type'],
//            'amount'=>$post['amount'],
//            'sign'=>2,
//            'chargetype'=>1,
//            'charge_cn'=>"会员充值",
//            'addtime'=>time()
//        );
//        Db::name('user_wallet_log')->insert($data);
//        $result = $this->check_recharge_order($post);        //检查订单状态
//        if ($result["status"] == 0) {
//            $this->error($result["msg"]);
//        }
//        $out_trade_no = $post['order_sn'];
//        $total_fee = $post['final_amount'] * 100;
        $order = db('user_wallet_log')->where('order_sn',$post['order_sn'])->find();
        $this->assign('final_amount',$order['amount']);
        $order['amount'] = $order['amount']*100;
//        $order['amount'] = 1;
        //微信浏览器端
        $pay = 	&load_wechat('Pay');
        if (!empty(session("openid")) && is_weixin()) {
            $pay = &load_wechat('Pay');
            $openid = session("openid");
            $notify_url = $root.url("@index/notify/wx_notifyrecharge");
            $body = "会员充值";

            $prepayid = $pay->getPrepayId($openid, $body, $order['order_sn'], $order['amount'], $notify_url, $trade_type = "JSAPI");
            //更新预支付
            $prepaydata = ["prepayid" => $prepayid];
            Db::table("ys_user_wallet_log")->where("order_sn", $order['order_sn'])->update($prepaydata);

            $options = $pay->createMchPay($prepayid);
            $this->assign('options', json_encode($options));
            $this->assign('out_trade_no',$order['order_sn']);
            $this->assign('sign',2);                //会员充值
            $this->assign('title','会员充值');        //会员充值

            return view("weixinpay/weixin_pay");
        }else{
            $pay          = 	& load_wechat('Pay');
            $body         ="会员充值";
//            $order['amount'] = 1;
            $notify_url   = $root.url("@index/notify/notifyweixinpay_code");
            $prepayid 	  =$pay->getPrepayId(null, $body, $order['order_sn'],$order['amount'],$notify_url,     $trade_type = "NATIVE");
            //更新预支付
            $prepaydata= ["prepayid"=>$prepayid];
            Db::table("ys_user_wallet_log")->where("order_sn",$order['order_sn'])->update($prepaydata);
            $this->assign('prepayid',$prepayid);
            $this->assign('out_trade_no',$order['order_sn']);
            $this->assign('sign',2);        //会员充值
            $this->assign('title','会员充值');        //会员充值

            return view("weixinpay/weixin_code");
        }
    }

    /**
     * @Author lignyun
     * @Desc    会员充值 -- 二维码
     * @param   id   user_wallet_log  主键ID
     * 2018-03-21
     */
    public function recharge_code(){
        $root = request()->domain();
        $post = input('param.');
        //预支付检查订单
        $flag = $this->check_recharge_order($post);
        if($flag['status'] == 0){       //订单失败
            $this->assign('err_msg','订单信息有误，请重新充值');
            $this->assign('err_url',url('User/recharge'));
            $this->assign('err_button','重新充值');
            return $this->fetch('public/error');
            exit();
        }

//        $post['final_amount'] = $post['amount'];
//        $data = array(
//            'uid'=>$post['uid'],
//            'admin_id'=>0,
//            'store_id'=>0,
//            'order_id'=>0,
//            'order_sn'=>$post['order_sn'],
//            'pay_status'=>0,
//            'pay_type'=>$post['pay_type'],
//            'amount'=>$post['amount'],
//            'sign'=>2,
//            'chargetype'=>1,
//            'charge_cn'=>"会员充值",
//            'addtime'=>time()
//        );
//        Db::name('user_wallet_log')->insert($data);
        $order = db('user_wallet_log')->where('id',$post['id'])->find();
        $pay          = 	& load_wechat('Pay');
        $body         ="会员充值";
        $order['amount'] = 1;
        $notify_url   = $root.url("@index/notify/notifyweixinpay_code");
        $prepayid 	  =$pay->getPrepayId(null, $body, $order['order_sn'],$order['amount'],$notify_url,     $trade_type = "NATIVE");
        //更新预支付
        $prepaydata= ["prepayid"=>$prepayid];
        Db::table("ys_user_wallet_log")->where("order_sn",$order['order_sn'])->update($prepaydata);
        $this->assign('prepayid',$prepayid);
        $this->assign('out_trade_no',$order['order_sn']);
        $this->assign('sign',2);        //会员充值
        $this->assign('title','会员充值');        //会员充值

        return view("weixinpay/weixin_code");
        exit;
    }

    /**
     * @Author  lignyun
     * @Desc    购买代金券 微信 -- 扫码通用
     */
    public function buy_cash_coupon(){
        $root = request()->domain();
        $post = input('param.');
        $uid = session('_user_uid_.uid');
        $coupon = db('store_coupon')->where('id',$post['id'])->find();
        $this->assign('final_amount',$coupon['price']);
        $data_arr = [
            'order_sn'=>create_order_sn($uid),
            'uid'=>$uid,
            'cash_coupon_id'=>$post['id'],
            'store_id'=>session('store_id'),
            'pay_time'=>time(),
            'pay_type'=>$post['pay_type'],
            'price'=>$coupon['price'],
            'addtime'=>time(),
            'remark'=>'待支付',
        ];
        //插入支付订单
        $res = db('cash_coupon_list')->insert($data_arr);

        $out_trade_no = $data_arr['order_sn'];
        $total_fee    =  $data_arr['price']*100;
//        $total_fee = 1;
        //微信浏览器端
        $pay          = 	& load_wechat('Pay');
        if(!empty(session("openid")) && is_weixin()){
            $pay          =  & load_wechat('Pay');
            $openid       =  session("openid");
            $notify_url   = $root.url("@index/notify/wx_buy_coupon_notify");
            $body         = "微信支付";

            $prepayid = $pay->getPrepayId($openid, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "JSAPI");
            //更新预支付
            $prepaydata= ["prepayid"=>$prepayid];
            Db::table("ys_order")->where("order_sn",$out_trade_no)->update($prepaydata);

            $options = $pay->createMchPay($prepayid);
            $this->assign('options',json_encode($options));
            $this->assign('out_trade_no',$out_trade_no);
            $this->assign('sign',3);
            return view("weixinpay/weixin_pay");
        }

        $body         =  "微信扫码支付";
        $notify_url   =  $root.url("@index/notify/wx_buy_coupon_notify");
        $prepayid 	  =  $pay->getPrepayId(null, $body, $out_trade_no,$total_fee,$notify_url, $trade_type = "NATIVE");
        //更新预支付
        $prepaydata= ["prepayid"=>$prepayid];
        db("cash_coupon_list")->where("order_sn",$data_arr['order_sn'])->update($prepaydata);
        $this->assign('prepayid',$prepayid);
        $this->assign('out_trade_no',$out_trade_no);
        $this->assign('sign',3);
        return view("weixinpay/weixin_code");
        exit;
    }

    /**
     * @Author lignyun
     * @Desc    预支付 -- 检查充值订单
     * 2018-03-21
     */
    private function check_recharge_order($post){
        if(empty($post['order_sn'])){
            $this->assign('err_msg','找不到订单信息，请重新充值');
            $this->assign('err_url',url('User/recharge'));
            $this->assign('err_button','重新充值');
            return $this->fetch('public/error');
            exit();
        }else{
            $order = Db::name('user_wallet_log')->where("order_sn",$post['order_sn'])->find();
            if(empty($order)){
                $this->assign('err_msg','找不到订单信息，请重新充值');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if($order['pay_status'] == 1){
                $this->assign('err_msg','该订单已支付，请勿重复支付');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }else if(time()-3600>$order["addtime"]){
                $this->assign('err_msg','该订单已过期，请重新下单');
                $this->assign('err_url',url('User/recharge'));
                $this->assign('err_button','重新充值');
                return $this->fetch('public/error');
                exit();
            }
        }
        return ['status'=>1,'msg'=>'找到订单'];
    }

    /**
     * @Author  lingyun
     * @Desc    轮询查询会员充值的结果，完成进行跳转页面
     * @return array
     */
    public function recharge_sn_ajax(){
        $order_sn = request()->get("out_trade_no");
        $order = db("user_wallet_log")->where("order_sn",$order_sn)->find();
//        if($order['addtime']<time()-864000){
//            return ['code'=>-1,'msg'=>'支付订单已关闭，请重新创建订单'];
//        }
        if($order["pay_status"] == 1){
            return ["status"=>1,"msg"=>'支付完成'];
        }else if($order['pay_status'] == -1){
            $msg = empty($order['charge_cn'])?'支付失败，请重新支付':$order['charge_cn'];
            return ["status"=>-1,"msg"=>$msg];
        }
    }

    /**
     * @Author  lingyun
     * @Desc    轮询查询代金券的支付情况
     * 2018-05-04
     */
    public function cash_coupon_sn_ajax(){
        $order_sn = input('out_trade_no');
        $order = db('cash_coupon_list')->where('order_sn',$order_sn)->find();
        if($order['pay_status'] == 1){
            return ["status"=>1,"msg"=>'支付完成'];
        }else{
            return ["status"=>0,"msg"=>'支付失败'];
        }
    }

}